//index.js

const {
  calculate,
  OPERATOR,
  REG_DECIMAL,
  isDecimal,
  DEVIDE_ZERO_ERROR,
} = require("../../utils/util")

const getInputHisStr = function (arr) {
  return (arr && arr.length) ? arr.join(' ') : ''
}

Page({
  data: {
    inputHistoryArr: [],
    inputHistoryStr: '',
    current: '0',
    appendFlag: false,
    stack: [],
    complete: false,
    errorFlag: false,
  },

  // 进入扫雷
  moveToGame: function () {
    wx.navigateTo({
      url: '../mine_clearance/chooseLevel/chooseLevel'
    })
  },

  onLoad: function () {
  },

  /**
   * 计算器交互函数
   * @param {event} e 事件对象
   */
  onInput(e) {

    const buttonType = e.target.dataset.buttonType
    const value = e.target.dataset.value
    let stack = this.data.stack

    let current = this.data.current + ''

    // 点击了数值
    if (buttonType === 'number') {
      if (this.data.complete) {
        stack.splice(0)
        this.data.inputHistoryArr.splice(0)
        this.setData({
          inputHistoryStr: '',
          complete: false
        })
      }
      if (this.data.appendFlag && this.data.current != '0') {
        current = this.data.current + '' + (current.length > 10 ? '' : value)
        stack.pop()
      } else {
        current = value
      }
      stack.push(current)
      this.data.appendFlag = true
      this.data.errorFlag = false

      this.setData({
        current
      })
    }
    // 点击了非数字
    else {
      const operator = OPERATOR[value]
      let inputHistoryArr = this.data.inputHistoryArr
      let previous = current

      switch (value) {

        case 'clearError':  // 清空当前内容
          if (this.data.complete) {
            inputHistoryArr.splice(0)
            stack.splice(0)
            this.setData({
              inputHistoryStr: '',
              current: 0,
              appendFlag: false
            })
          } else {
            this.data.appendFlag && stack.pop()
            this.setData({
              current: 0,
              appendFlag: false
            })
          }
          break

        case 'clear':       // 清空所有内容
          inputHistoryArr.splice(0)
          stack.splice(0)
          this.setData({
            inputHistoryStr: '',
            current: 0,
            appendFlag: false
          })
          break

        case 'backspace':   // 回退
          if (this.data.appendFlag) {
            let temp = Array.from(this.data.current + '')
            temp.pop()
            current = temp.join('') || 0
            stack.pop()
            current && stack.push(current)
            this.setData({
              current
            })
          }
          break

        case 'divide':      // 除法运算
        case 'multiply':    // 乘法运算
        case 'minus':       // 减法运算
        case 'add':         // 加法运算
        case 'equal':       // 运算结果
          if (this.data.errorFlag) return

          if (this.data.appendFlag || inputHistoryArr.length === 0) {
            // calculate
            if (stack.length === 0) {
              stack.push(0)
            } else if (stack.length > 1) {
              let opCount = inputHistoryArr.length
              let lastOperator = inputHistoryArr.slice(opCount - 1, opCount)[0]
              current = calculate(stack[0], stack[1], lastOperator)
              this.data.errorFlag = this.data.complete = current === DEVIDE_ZERO_ERROR
              stack.splice(0)
              !this.data.errorFlag && stack.push(current)
            }

            if (value === 'equal') {
              inputHistoryArr = this.data.inputHistoryArr = []
            } else {
              inputHistoryArr.push(previous)
              inputHistoryArr.push(operator)
            }
          } else if (value === 'equal') {
            inputHistoryArr = this.data.inputHistoryArr = []
            if (stack.length === 1) {
              current = stack[0]
            }
          } else {
            inputHistoryArr.pop()
            inputHistoryArr.push(operator)
          }

          this.setData({
            current,
            inputHistoryStr: getInputHisStr(inputHistoryArr)
          })
          this.data.appendFlag = false
          break

        case 'negate':      // 正负取反
          if (this.data.errorFlag) return

          // 如果为0或'0'，不处理
          if (this.data.current == 0) {
            break
          }

          // 如果非0，则乘以 -1
          let current = this.data.current * -1

          stack.pop()
          stack.push(current)

          this.setData({
            current
          })

          break

        case 'decimal':     // 小数点
          if (this.data.errorFlag) return
          
          // 输入模式下，判断是否为小数
          if (this.data.appendFlag) {
            // 如果已经是小数，则不处理
            // 如果不是小数，在尾追加[.]
            if (!isDecimal(this.data.current, REG_DECIMAL)) {
              let temp = this.data.current + '.';
              stack.pop()
              stack.push(temp)
              this.setData({current: temp})
            }
          }
          // 其它：直接[0.?]
          else {
            let temp = '0.';
            this.data.complete && stack.splice(0)
            stack.push(temp)
            this.data.appendFlag = true
            this.setData({ current: temp })
          }
          
          break
      }

      this.data.complete = (value === 'equal') || this.data.errorFlag
    }
  },
  onShareAppMessage: function() {
    return {
      title: 'mini计算器',
      path: '/pages/index/index.js'
    }
  }
})
